import 'dart:async';

import 'package:flutter/services.dart';

typedef Future<dynamic> EventHandler(Map<String, dynamic> event);

class XunfeiListener {
  Function(dynamic result) onResult;

  XunfeiListener({this.onResult});

}

class FlutterXunfei {
  FlutterXunfei._();

  static final FlutterXunfei xunfei = FlutterXunfei._();

  static const MethodChannel _channel = const MethodChannel('flutterXunfei');

  /// 创建讯飞语音识别
  Future<void> initIat({String appid, XunfeiListener listener}) {
    _channel.invokeMethod("initIat", {"APPid": appid});
    _channel.setMethodCallHandler((MethodCall call) async {
      String method = call.method;
      if (method == "initResult") listener.onResult(call.arguments);
    });
  }

  /// 创建语音唤醒
  Future<void> initIvw({String appid, XunfeiListener listener}) {
    _channel.invokeMethod("initIvw", {"APPid": appid});
    _channel.setMethodCallHandler((MethodCall call) async {
      String method = call.method;
      if (method == "initResult") listener.onResult(call.arguments);
    });
  }

  /// 开始语音识别
  Future<void> startIat({XunfeiListener listener}) async {
    int ret = await _channel.invokeMethod("startIat");
    if (ret == 0) {
      _channel.setMethodCallHandler((MethodCall call) async {
        String method = call.method;
        if (method == "onIatResult") listener.onResult(call.arguments.cast<String, dynamic>());
      });
    } else {
      print("语音识别开启失败");
    }
  }

  /// 停止语音识别
  Future<void> stopIat() async {
    int ret = await _channel.invokeMethod("stopIat");
    if (ret == 0) {
      print("语音识别停止成功");
    } else {
      print("语音识别停止失败");
    }
  }

  /// 取消语音识别
  Future<void> cancelIat() async {
    int ret = await _channel.invokeMethod("cancelIat");
    if (ret == 0) {
      print("语音识别取消成功");
    } else {
      print("语音识别取消失败");
    }
  }

  /// 开启语音唤醒
  Future<void> openIvw({XunfeiListener listener}) async {
    int ret = await _channel.invokeMethod("openIvw");
    if (ret == 0) {
      print("开启语音唤醒成功");
      _channel.setMethodCallHandler((MethodCall call) async {
        String method = call.method;
        if (method == "onIvwResult") listener.onResult(call.arguments);
      });
    } else {
      print("开启语音唤醒失败");
    }
  }

  /// 关闭语音唤醒
  Future<void> closeIvw() async {
    int ret = await _channel.invokeMethod("closeIvw");
    if (ret == 0) {
      print("关闭语音唤醒成功");
    } else {
      print("关闭语音唤醒失败");
    }
  }
}
